package com.anonymous.community.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.anonymous.community.PostDetailActivity;
import com.anonymous.community.R;
import com.anonymous.community.api.ApiClient;
import com.anonymous.community.api.ApiService;
import com.anonymous.community.api.model.LikeResponse;
import com.anonymous.community.api.model.PostListResponse;
import com.anonymous.community.model.Post;
import com.anonymous.community.ui.base.BaseFragment;
import com.anonymous.community.utils.TokenManager;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 推荐Fragment
 * 显示热门推荐帖子
 */
public class RecommendFragment extends BaseFragment implements PostAdapter.OnPostInteractionListener {

    private SwipeRefreshLayout swipeRefresh;
    private RecyclerView recyclerView;
    private PostAdapter adapter;
    private List<Post> postList;
    private ApiService apiService;
    private int currentPage = 1;
    private boolean isLoading = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend, container, false);
        
        apiService = ApiClient.getApiService();
        postList = new ArrayList<>();
        
        initViews(view);
        setupRecyclerView();
        setupSwipeRefresh();
        loadPosts(true);
        
        return view;
    }

    private void initViews(View view) {
        swipeRefresh = view.findViewById(R.id.swipe_refresh);
        recyclerView = view.findViewById(R.id.post_recycler_view);
    }

    private void setupRecyclerView() {
        adapter = new PostAdapter();
        adapter.setOnPostInteractionListener(this);
        
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        
        // 分页加载
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null && !isLoading) {
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                    
                    if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                            && firstVisibleItemPosition >= 0) {
                        loadPosts(false);
                    }
                }
            }
        });
    }

    private void setupSwipeRefresh() {
        swipeRefresh.setOnRefreshListener(() -> {
            currentPage = 1;
            loadPosts(true);
        });
        swipeRefresh.setColorSchemeColors(getResources().getColor(R.color.black));
    }

    /**
     * 加载帖子列表 - 使用hot排序（热门）
     */
    private void loadPosts(boolean refresh) {
        if (isLoading) return;
        
        isLoading = true;
        if (refresh) {
            currentPage = 1;
            swipeRefresh.setRefreshing(true);
        }
        
        apiService.getPosts(currentPage, 20, "hot", null)
                .enqueue(new Callback<PostListResponse>() {
                    @Override
                    public void onResponse(Call<PostListResponse> call, Response<PostListResponse> response) {
                        isLoading = false;
                        swipeRefresh.setRefreshing(false);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            PostListResponse postListResponse = response.body();
                            List<PostListResponse.PostItem> items = postListResponse.getPosts();
                            
                            if (items != null && !items.isEmpty()) {
                                List<Post> posts = convertToPosts(items);
                                
                                if (refresh) {
                                    postList.clear();
                                    postList.addAll(posts);
                                    adapter.setPosts(postList);
                                } else {
                                    postList.addAll(posts);
                                    adapter.addPosts(posts);
                                }
                                
                                currentPage++;
                            }
                        } else {
                            Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<PostListResponse> call, Throwable t) {
                        isLoading = false;
                        swipeRefresh.setRefreshing(false);
                        Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private List<Post> convertToPosts(List<PostListResponse.PostItem> items) {
        List<Post> posts = new ArrayList<>();
        for (PostListResponse.PostItem item : items) {
            Post post = new Post();
            post.setId(String.valueOf(item.getId()));
            post.setContent(item.getContent());
            post.setUsername(item.getAnonymousId());
            post.setLikes(item.getLikeCount());
            post.setComments(item.getCommentCount());
            post.setShares(0);
            post.setLiked(item.isLiked());
            post.setAnonymous(true);
            post.setTimestamp(System.currentTimeMillis());
            posts.add(post);
        }
        return posts;
    }

    @Override
    public void onLikeClick(int position) {
        if (position < postList.size()) {
            Post post = postList.get(position);
            String token = TokenManager.getToken(requireContext());
            
            if (token == null || token.isEmpty()) {
                Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            
            int postId = Integer.parseInt(post.getId());
            apiService.toggleLike(token, "post", postId)
                    .enqueue(new Callback<LikeResponse>() {
                        @Override
                        public void onResponse(Call<LikeResponse> call, Response<LikeResponse> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                LikeResponse likeResponse = response.body();
                                post.setLiked(likeResponse.isLiked());
                                post.setLikes(likeResponse.getLikeCount());
                                adapter.notifyItemChanged(position);
                            }
                        }

                        @Override
                        public void onFailure(Call<LikeResponse> call, Throwable t) {
                            Toast.makeText(getContext(), "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    @Override
    public void onCommentClick(int position) {
        if (position < postList.size()) {
            Post post = postList.get(position);
            Intent intent = new Intent(requireContext(), PostDetailActivity.class);
            intent.putExtra("post_id", Integer.parseInt(post.getId()));
            startActivity(intent);
        }
    }

    @Override
    public void onShareClick(int position) {
        Toast.makeText(getContext(), "分享功能开发中", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMoreClick(int position) {
        Toast.makeText(getContext(), "更多选项", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUserClick(int position) {
        // 匿名社区不显示用户主页
    }

    @Override
    protected String getPageName() {
        return "推荐页";
    }
}
